<?php
namespace App\Api\Controllers;

use App\Models\Order;
use App\Models\Stock;
use App\Models\StocksOrder;
use App\Models\User;
use App\Api\Requests\UserRequest;
use Dingo\Api\Http\Request;
use App\Models\UserLog;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use Illuminate\Support\Facades\DB;
class StocksController extends Controller
{
    public function index(Stock $stock){
        return $this->success($stock->where("on_sale",1)->orderBy('id','desc')->get());
    }

    //购买
    public function purchase(Stock $stock,StocksOrder $stocksOrder){
        $order_id = $_GET["id"];

        $order=$stock->where("id",$order_id)->first();
       if( $order->price> $this->user()->balance){
            return $this->error('余额不足');
        }
        $stocksOrder->member_id = $this->user()->id;
        $stocksOrder->order_no = time();
        $stocksOrder->symbol_code =  $order->code;
        $stocksOrder->volume =  1;
        $stocksOrder->open_time =  time();
        $stocksOrder->rebate_type =   $order->rebate_type;
        $stocksOrder->rebate_cycle =  $order->rebate_cycle;
        $stocksOrder->rebate =  $order->rebate;
        if( $stocksOrder->save()){
            //扣减BTC
            (new UserLog())->change(-$order->price,81,'balance',43,'购买股权');
                DB::table('users')->where('id', '=', $this->user()->id)->update(['balance' => $this->user()->balance-$order->price]);

        }
    }


    //股权收益
    public function profit(StocksOrder $stocksOrder){


        $order_id = $_GET["id"];
        $order=$stocksOrder->where("id",$order_id)->first();

        if (time() - $order->open_time < 24 * 3600) {
            return $this->error('结算间隔不到24小时！');
        }


        $a_time = (time() - $order->open_time)/3600;
        $shoyi = ($a_time/$order->rebate_cycle)*$order->rebate;
        if ($order->rebate_type=="m"){}else{}
//        if($coin->save()){
//            //扣减BTC
//            (new UserLog())->change(-$coin->btc,$this->user()->id,'btc',43,'会员提币');
//        }
     //   return $this->success($coin);
    }



}